package com.javajun.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.javajun.custom.BaseService;
import com.javajun.entity.Claxx;
import com.javajun.form.ClaxxForm;

@Service
public class ClaxxService extends BaseService<Claxx, Integer>{

	public Specification<Claxx> BuildSpec(ClaxxForm form) {
		Specification<Claxx> spec = new Specification<Claxx>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Claxx> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				// 一个永远成立的条件
				predicates.add(cb.greaterThan(root.get("id"), 0));
				if (StringUtils.hasText(form.getName())) {
					predicates.add(cb.like(root.get("name"), "%" + form.getName() + "%"));
				}
				if (form.getManagerId() != null) {
					predicates.add(cb.equal(root.get("manager").get("id"), form.getManagerId()));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};
		return spec;
	}
}
